/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package session;

import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import persistance.Username;

/**
 *
 * @author Andreea
 */
@Stateless
public class UsernameSessionBean implements UsernameSessionBeanRemote {
    @PersistenceContext(unitName = "FamilyDoctorAssistant-ejbPU")
    private EntityManager em;

    public void persist(Object object) {
        em.persist(object);
    }

    // Add business logic below. (Right-click in editor and choose
    // "Insert Code > Add Business Method")

    @Override
    public void addUsername(String username, String password) {
        Username u=new Username();
        u.setUsername(username);
        u.setPassword(password);
        em.persist(u);
    }
     public Username findUser(String username, String password) {
        Username user = null;
        Query query = em.createQuery("SELECT u from Username u WHERE u.username=:username AND u.password=:password");
        query.setParameter("username", username);
        query.setParameter("password", password);
        if (query.getResultList().size() > 0) {
            user = (Username) query.getResultList().get(0);
        }
        return user;
    }

    @Override
    public long login(String username, String password) {
        Username u=this.findUser(username, password);
        if (u!=null){
            return u.getId();
        }
        else
            return 0;
    }
    
}
